package sdk.webview.fmc.com.fmcsdk.check.activity;

import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_NOTIFY_H5_BACK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sdk.webview.fmc.com.fmcsdk.BaoTipEvent;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.CameraOneActivity;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.ImageEditActivity;
import sdk.webview.fmc.com.fmcsdk.activity.RecordVideoActivity;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BindEventBus;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.camera.AppConstant;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ImagePagerAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ImageSelectAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.ImageSelectBean;
import sdk.webview.fmc.com.fmcsdk.check.dialog.BottomPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.dialog.CenterPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.WaterMeterView;
import sdk.webview.fmc.com.fmcsdk.check.listener.RequestPermissionsListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.StartH5Event;
import sdk.webview.fmc.com.fmcsdk.check.persenter.WaterMeterPresenter;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.upload.ImageUploadBean;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.FileUtil;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.ImageCompressor;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.SoftKeyBoardListener;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.view.CreamOrVideoRecordDialog;
import top.zibin.luban.OnCompressListener;

@BindEventBus
public class WaterMeterActivity extends BaseActivity<WaterMeterView, WaterMeterPresenter> implements WaterMeterView {
    private GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item;
    private TextView tv_water_meter, tv_water_meter_name, tv_normal_range_value,
            tv_remake_font_count, tv_dispatch_order, tv_num, tv_remake_must, tv_photo_must;
    private EditText et_remake, et_value;
    private RecyclerView rv_img;
    private ImageView iv_back;
    private String imageName = "";
    public static final int TAKEPIC_H5 = 201;
    private static final int IMAGEEDIT_OK = 202;
    List<String> permissionLists10 = new ArrayList<>();
    List<String> permissionLists11 = new ArrayList<>();
    List<String> permissionLists12 = new ArrayList<>();
    List<String> permissionLists13 = new ArrayList<>();

    private ImageSelectAdapter imageSelectAdapter;

    private DatabaseManager databaseManager;
    private Snackbar snackbar;
    private String detailId, assetId, projId, managerName, managerPhone, managerId;
    private int position;
    private GetDetailsBean.RecordDTO.PointsDTO pointsDTO;
    private GetDetailsBean getDetailsBean;
    private GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO recordItem = null;
    private int recordPosition = -1;

    private boolean isShowErrorPopup = false;
    private List<ImageSelectBean> recordList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_water_meter;
    }
private View view_bootom;
    @Override
    protected void init(Bundle savedInstanceState) {
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }

        String data = getIntent().getStringExtra("data");
        if (null != data) {
            item = GsonUtil.GsonToBean(data, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.class);
        }

        detailId = getIntent().getStringExtra("detailId");
        assetId = getIntent().getStringExtra("assetId");
        projId = getIntent().getStringExtra("projId");
        managerName = getIntent().getStringExtra("managerName");
        managerPhone = getIntent().getStringExtra("managerPhone");
        managerId = getIntent().getStringExtra("managerId");
        position = getIntent().getIntExtra("position", 0);
        //isMustWorkOrder = getIntent().getBooleanExtra("isMustWorkOrder", false);
        String pointData = getIntent().getStringExtra("pointsDTO");
        if (null != pointData) {
            pointsDTO = GsonUtil.GsonToBean(pointData, GetDetailsBean.RecordDTO.PointsDTO.class);
        }

        String detailBeanData = getIntent().getStringExtra("getDetailsBean");
        if (null != detailBeanData) {
            getDetailsBean = GsonUtil.GsonToBean(detailBeanData, GetDetailsBean.class);
        }
        initView();
        initData();
        initRecycler();
        initListener();
        SoftKeyBoardListener.setListener(WaterMeterActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if(view_bootom==null)return;
                view_bootom.setVisibility(View.VISIBLE);
                KLog.e("show");
            }

            @Override
            public void keyBoardHide(int height) {
                if(view_bootom==null)return;
                view_bootom.setVisibility(View.GONE);
                KLog.e("dismiss");
            }
        });

    }

    private void setBackData() {
        Intent intent = new Intent();
        intent.putExtra("position", position);
        intent.putExtra("item", GsonUtil.BeanToJson(item));
        setResult(AppConstant.RESULT_CODE.RESULT_OK, intent);
        EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
        finish();
    }

    @SuppressLint("SetTextI18n")
    private void initListener() {
        iv_back.setOnClickListener(v -> {
            if (!StringUtils.isEmpty(et_value.getText().toString())) {
                if (!isShowErrorPopup) {  //当前不显示异常的弹窗
                    setBackData();
                }
            } else {
                setBackData();
            }
        });

        et_remake.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            @Override
            public void afterTextChanged(Editable editable) {
                tv_remake_font_count.setText(editable.length() + "/" + "100");
                if (editable.length() > 100) {
                    editable.delete(100, editable.length());
                }
            }
        });
        setOnFocusChangeListener(et_remake);
        setOnFocusChangeListener(et_value);
        setOnEditorActionListener(et_remake);
        setOnEditorActionListener(et_value);


        //派单
        tv_dispatch_order.setOnClickListener(v -> {
            showErrorDialog(v, item);
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            et_value.clearFocus();
            if (!StringUtils.isEmpty(et_value.getText().toString())) {
                if (!isShowErrorPopup) {  //当前不显示异常的弹窗
                    setBackData();
                }
            } else {
                setBackData();
            }
            return true; // 返回true表示已经处理了这个按键事件
        }
        return super.onKeyDown(keyCode, event);
    }


    private void setOnEditorActionListener(EditText edittext) {
        edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) {
                // 判断是否是回车键，actionId 为 IME_ACTION_DONE
                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    if (edittext.getId() == R.id.et_value) {
                        if (StringUtils.isEmpty(et_value.getText().toString())) {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, context.getResources().getString(R.string.Please_enter_the_value));
                        }
                    }

                    // 关闭软键盘（可选）
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    edittext.clearFocus();

                    return true; // 返回 true 表示事件已经处理
                }
                return false;
            }
        });
    }

    private boolean isCheckPass() {
        if (item.getMustFillRemark() != 0) {
            if (StringUtils.isEmpty(item.getRemark())) {
                //备注必填 但是没填
                return false;
            }
        }

        if (item.getMustTakePic() != 0) {
            if (item.getPictureUrls().isEmpty()) {
                //拍照必填 但是没填
                return false;
            }
        }

        if (!StringUtils.isEmpty(item.getMeterRead())) {
            if (null != item.getAlertLowLimit() && null != item.getAlertUpLimit()) {  //下限值和上限值都不为空
                BigDecimal meterRead = new BigDecimal(item.getMeterRead());

                if (meterRead.compareTo(item.getAlertLowLimit()) < 0) {  //输入的水表值低于下线 说明是异常现象
                    //已经报过异常了
                    if (item.getAbnormal() == 1) {
                        item.setChecked(1);
                        return true;
                    } else {
                        return false;
                    }
                }


                if (meterRead.compareTo(item.getAlertUpLimit()) > 0) { //输入的水表值高于上线 说明是异常现象
                    //已经报过异常了
                    if (item.getAbnormal() == 1) {
                        item.setChecked(1);
                        return true;
                    } else {
                        return false;
                    }
                }

                item.setChecked(1);
                return true;

            } else {
                if (null == item.getAlertLowLimit() && null == item.getAlertUpLimit()) { //下限值为空  上限值也为空  那输入任何的值都算是已检
                    item.setChecked(1);
                    return true;
                } else {
                    BigDecimal meterRead = new BigDecimal(item.getMeterRead());
                    if (null == item.getAlertLowLimit()) { //下限值为空
                        if (meterRead.compareTo(item.getAlertLowLimit()) < 0) {  //输入的水表值低于下线 说明是异常现象
                            //已经报过异常了
                            if (item.getAbnormal() == 1) {
                                item.setChecked(1);
                                return true;
                            } else {
                                return false;
                            }
                        } else {
                            item.setChecked(1);
                            return true;
                        }

                    } else {  //也就是上限值为空
                        if (meterRead.compareTo(item.getAlertUpLimit()) > 0) { //输入的水表值高于上线 说明是异常现象
                            //已经报过异常了
                            if (item.getAbnormal() == 1) {
                                item.setChecked(1);
                                return true;
                            } else {
                                return false;
                            }
                        } else {  //说明在范围
                            item.setChecked(1);
                            return true;
                        }
                    }
                }
            }

        } else { //没有填写检测值
            return false;
        }


    }

    private void setOnFocusChangeListener(EditText editText) {
        editText.setOnFocusChangeListener((view, b) -> {
            if (!b) {
                if (view.getId() == R.id.et_remake) {
                    String newText = editText.getText().toString();
                    item.setRemark(newText);
                    isCheckPass();
                } else if (view.getId() == R.id.et_value) {
                    if (!StringUtils.isEmpty(et_value.getText().toString())) {
                        String value = et_value.getText().toString();
                        if (null != item) {
                            item.setMeterRead(value);
                            if (TextUtils.isEmpty(value) || TextUtils.equals(value, ".")) return;
                            BigDecimal bigValue = new BigDecimal(value);
                            if (null != item.getAlertLowLimit() && null != item.getAlertUpLimit()) {
                                if (bigValue.compareTo(item.getAlertLowLimit()) < 0) {
                                    showErrorDialog(et_value, item);
                                } else if (bigValue.compareTo(item.getAlertUpLimit()) > 0) {
                                    showErrorDialog(et_value, item);
                                } else {
                                    boolean checkPass = isCheckPass();
                                    item.setAbnormal(0);
                                }
                            }


                        }
                    }


                }
            }

        });
    }

    private void showAbnormalPopupWindow(View anchor, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item, StartWorkActivity.OnAbnormalPopupWindowListener listener) {
        BottomPopupWindow abnormalPopupWindow = new BottomPopupWindow(context, R.layout.dialog_work_error);
        View contentView = abnormalPopupWindow.getContentView();
        TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
        EditText etContent = contentView.findViewById(R.id.et_content);
        TextView tvFontNumber = contentView.findViewById(R.id.tv_font_number);
        LinearLayout ll_work_tick = contentView.findViewById(R.id.ll_work_tick); //报工单
        TextView tv_work_tick_required = contentView.findViewById(R.id.tv_work_tick_required); // 报工单 星号键
        LinearLayout ll_entry_requirement = contentView.findViewById(R.id.ll_entry_requirement); //报单需求
        TextView tv_entry_requirement_required = contentView.findViewById(R.id.tv_entry_requirement_required); //报单需求 星号键
        TextView tv_save_no_declaration = contentView.findViewById(R.id.tv_save_no_declaration); //保存不报单
        view_bootom=contentView.findViewById(R.id.view_bootom);
        GetDetailsBean.RecordDTO.ExceptionReportDTO exceptionReport = getDetailsBean.getRecord().getExceptionReport();
        if (null != exceptionReport) {
            String exceptionReportValue = exceptionReport.getExceptionReport();
            if (!StringUtils.isEmpty(exceptionReportValue)) {
                if (TextUtils.equals("2", exceptionReportValue) || TextUtils.equals("4", exceptionReportValue) || TextUtils.equals("5", exceptionReportValue) || TextUtils.equals("6", exceptionReportValue)) {
                    //报需求单 显示
                    ll_entry_requirement.setVisibility(View.VISIBLE);
                    if ((exceptionReportValue.equals("4") || exceptionReportValue.equals("6")) && StringUtils.isEmpty(item.getWorkOrderId())) {
                        //报需求单显示星号键
                        tv_entry_requirement_required.setVisibility(View.VISIBLE);
                    } else {
                        tv_entry_requirement_required.setVisibility(View.GONE);
                    }
                }

                if (TextUtils.equals("1", exceptionReportValue) || TextUtils.equals("3", exceptionReportValue) || TextUtils.equals("5", exceptionReportValue) || TextUtils.equals("6", exceptionReportValue)) {
                    //报工单 显示
                    ll_work_tick.setVisibility(View.VISIBLE);
                    if ((exceptionReportValue.equals("3") || exceptionReportValue.equals("6")) && StringUtils.isEmpty(item.getWorkOrderId())) {
                        // 报工单 显示 星号键
                        tv_work_tick_required.setVisibility(View.VISIBLE);
                    } else {
                        tv_work_tick_required.setVisibility(View.GONE);
                    }
                }


                if ((!TextUtils.equals("3", exceptionReportValue) && !TextUtils.equals("4", exceptionReportValue) && !TextUtils.equals("6", exceptionReportValue)) || !StringUtils.isEmpty(item.getWorkOrderId())) {
                    //保存不报单显示
                    tv_save_no_declaration.setVisibility(View.VISIBLE);
                    if (!StringUtils.isEmpty(item.getWorkOrderId())) {
                        tv_save_no_declaration.setText(context.getResources().getString(R.string.save));
                    } else {
                        tv_save_no_declaration.setText(context.getResources().getString(R.string.Save_no_declaration));
                    }
                }
            }
        }

        etContent.setText(null == item.getRemark() ? "" : item.getRemark());
        tvCancel.setOnClickListener(v -> {
            abnormalPopupWindow.dismiss();
            isShowErrorPopup = false;
        });

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                tvFontNumber.setText(s.length() + "/" + "100");
                if (s.length() > 100) {
                    s.delete(100, s.length());
                }
            }
        });

        ll_entry_requirement.setOnClickListener(v -> {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.onWorkTickClick(etContent.getText().toString(), item.getId(), tv_work_tick_required.getVisibility() == View.VISIBLE);
            abnormalPopupWindow.dismiss();

        });


        ll_work_tick.setOnClickListener(v -> {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.onWorkTickClick(etContent.getText().toString(), item.getId(), tv_work_tick_required.getVisibility() == View.VISIBLE);
            abnormalPopupWindow.dismiss();
        });

        tv_save_no_declaration.setOnClickListener(v -> {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.OnSaveNoDeclarationClick(etContent.getText().toString());
            abnormalPopupWindow.dismiss();
        });

        ll_entry_requirement.setOnClickListener(v -> {
            if (!NetworkUtils.isAvailable(context)) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getString(R.string.lixianbuyunx));
                return;
            }
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.onEntryRequirementClick(etContent.getText().toString(), item.getId(), tv_entry_requirement_required.getVisibility() == View.VISIBLE);
            abnormalPopupWindow.dismiss();

        });
        abnormalPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isShowErrorPopup = false;
            }
        });
        abnormalPopupWindow.show(anchor);
    }

    private void showErrorDialog(View view, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item) {
        isShowErrorPopup = true;
        showAbnormalPopupWindow(view, item, new StartWorkActivity.OnAbnormalPopupWindowListener() {
            @Override
            public void OnSaveNoDeclarationClick(String content) {
                if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                        (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {  //只要有必填未检的
                    item.setChecked(0);
                } else {
                    item.setChecked(1);
                }
                item.setMeterRead(et_value.getText().toString());
                item.setRemark(content);
                isShowErrorPopup = false;
            }

            @Override
            public void onWorkTickClick(String content, String inspectionItemId, boolean isMust) {
                String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");

                Map<String, String> paramsMap = new HashMap<>();
                paramsMap.put("orderId", detailId);
                paramsMap.put("pointId", pointsDTO.getId());
                paramsMap.put("taskId", presenter.getSharedPrefs().getString("taskId", ""));
                paramsMap.put("type", "inspChecklist");
                paramsMap.put("fromOrderId", pointsDTO.getOrderId());
                paramsMap.put("planPointId", pointsDTO.getPlanPointId());

                String remake = "";
                String locationDesc = "";
                String assetDesc = "";
                String serviceTypeDesc = "";
                String workerDesc = "";
                try {
                    remake = URLEncoder.encode("<" + item.getTitle() + ">" + getResources().getString(R.string.Find_an_anomaly) + "。" + content, "UTF-8");
                    locationDesc = URLEncoder.encode(pointsDTO.getLocationDesc(), "UTF-8");
                    assetDesc = URLEncoder.encode(pointsDTO.getAssetDesc(), "UTF-8");
                    serviceTypeDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeDesc()) ? "" : getDetailsBean.getRecord().getSysServiceTypeDesc()), "UTF-8");
                    workerDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getReportWorkerDesc()) ? "" : getDetailsBean.getRecord().getReportWorkerDesc()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                String url = "";
                if (NetworkUtils.isAvailable(WaterMeterActivity.this)) {
                    url = "#/srtask/apply";
                } else {
                    url = "#/srtask/offlinerepair";
                }
                String debug = "";
                if (sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false)) {
                    debug = "&isdebug=true";
                }

                String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken() + debug + url + "?assetId=" + assetId +
                        "&locationId=" + (StringUtils.isEmpty(pointsDTO.getLocationId()) ? "" : pointsDTO.getLocationId()) +
                        "&projId=" + projId +
                        "&locationDesc=" + locationDesc +
                        "&assetDesc=" + assetDesc +
                        "&description=" + remake +
                        "&questionDesc=" + remake +
                        "&requireType=SR&href=" + GsonUtil.BeanToJson(paramsMap) +
                        "&type=insp_check&requestWay=INSP_REPORT_1&staffTeamId=" + getDetailsBean.getRecord().getStaffTeamId() +
                        "&StaffTeamDesc=&workerId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getReportWorkerId()) ? "" : getDetailsBean.getRecord().getReportWorkerId()) +
                        "&workerDesc=" + workerDesc +
                        "&serviceTypeProjId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeId()) ? "" : getDetailsBean.getRecord().getSysServiceTypeId()) +
                        "&serviceTypeDesc=" + serviceTypeDesc +
                        "&gjId=" + detailId +
                        "&orderChklistId=" + item.getId() +
                        "&backRepair=3&inspDetailID=" + inspectionItemId +
                        "&from=app&imageList=" + new Gson().toJson(item.getPictureUrls()) +
                        "&formOrderId=" + pointsDTO.getOrderId() +
                        "&planPointId=" + pointsDTO.getPlanPointId();

                KLog.e(GsonUtil.BeanToJson(item.getPictureUrls()));

                if (!isMust) {  //工单非必填
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {  //当前还有必填项未填
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    //  item.setAbnormal(1);
                    item.setRemark(content);
                } else {
                    recordItem = item;
                    recordPosition = position;
                }

                isShowErrorPopup = false;
                item.setMeterRead(et_value.getText().toString());
                item.setRemark(content);
                EventBus.getDefault().post(new BaoTipEvent(h5Url));
                Intent intents = new Intent();
                intents.putExtra(Constant.H5_URL, h5Url);
                intents.setClass(context, H5Activity.class);
                Constant.isBao = true;
                intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivityForResult(intents, 20002);


            }

            @Override
            public void onEntryRequirementClick(String content, String inspectionItemId, boolean isMust) {
                String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                String nmeSrr = "";
                String locationDesc = "";
                String remake = "";
                String serviceTypeDesc = "";
                try {
                    nmeSrr = URLEncoder.encode((StringUtils.isEmpty(pointsDTO.getAssetDesc()) ? "" : pointsDTO.getAssetDesc()), "UTF-8");
                    locationDesc = URLEncoder.encode((StringUtils.isEmpty(pointsDTO.getLocationDesc()) ? "" : pointsDTO.getLocationDesc()), "UTF-8");
                    remake = URLEncoder.encode("<" + item.getTitle() + ">" + getResources().getString(R.string.Find_an_anomaly) + "。" + content, "UTF-8");
                    serviceTypeDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeDesc()) ? "" : getDetailsBean.getRecord().getSysServiceTypeDesc()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }

                String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken() + "#/srtask/requiresubmit?requestWay=INSP_REPORT_1&assetId=" + assetId +
                        "&assetName=" + nmeSrr +
                        "&locationId=" + (StringUtils.isEmpty(pointsDTO.getLocationId()) ? "" : pointsDTO.getLocationId()) +
                        "&locationDesc=" + locationDesc +
                        "&projId=" + projId +
                        "&contactPerson=" + (StringUtils.isEmpty(UserHelper.getUserName()) ? "" : UserHelper.getUserName()) +
                        "&reportByTel=" + (StringUtils.isEmpty(UserHelper.getUserPhone()) ? "" : UserHelper.getUserPhone()) +
                        "&reportBy=" + (StringUtils.isEmpty(UserHelper.getUserId()) ? "" : UserHelper.getUserId()) +
                        "&reportByName=" + (StringUtils.isEmpty(UserHelper.getUserName()) ? "" : UserHelper.getUserName()) +
                        "&orgId=" + UserHelper.getUserOwnerOrgId() +
                        "&orderId=" + (StringUtils.isEmpty(pointsDTO.getOrderId()) ? "" : pointsDTO.getOrderId()) +
                        "&pointId=" + pointsDTO.getId() +
                        "&taskId=" + presenter.getSharedPrefs().getString("taskId", "") +
                        "&serviceTypeProjId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeId()) ? "" : getDetailsBean.getRecord().getSysServiceTypeId()) +
                        "&serviceTypeDesc=" + serviceTypeDesc +
                        "&type=inspChecklist&descript-text=" + remake +
                        "&backRepair=3&inspDetailID=" + inspectionItemId +
                        "&from=app&imageList=" + new Gson().toJson(item.getPictureUrls());

                if (!isMust) { //需求单非必填
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) { //当前有必填项未填
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    // item.setAbnormal(1);
                    item.setRemark(content);
                } else {
                    recordItem = item;
                    recordPosition = position;
                }
                item.setMeterRead(et_value.getText().toString());
                item.setRemark(content);
                EventBus.getDefault().post(new BaoTipEvent(h5Url));
                isShowErrorPopup = false;
                Intent intents = new Intent();
                intents.putExtra(Constant.H5_URL, h5Url);
                intents.setClass(context, H5Activity.class);
                Constant.isBao = true;
                intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivityForResult(intents, 20002);


            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                // 判断点击是否在 EditText 区域外
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    v.clearFocus();  // 清除焦点
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // 隐藏软键盘
                    }
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }


    private void initRecycler() {
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> pictureUrls = item.getPictureUrls();
        List<ImageSelectBean> imageList = item.getImageList();
        for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrl : pictureUrls) {
            if (pictureUrl.getUrl().contains("mp4")) {
                imageList.add(new ImageSelectBean(pictureUrl.getUrl(), 2));
            } else {
                imageList.add(new ImageSelectBean(pictureUrl.getUrl(), 1));
            }

        }
        item.setImageList(imageList);
//        for (int i = imageList.size() - 1; i >= 0; i--) {
//            if (imageList.get(i).getType() == 0) {
//                imageList.remove(i);
//            }
//        }
        rv_img.setLayoutManager(new GridLayoutManager(context, 5));
        imageSelectAdapter = new ImageSelectAdapter(item.getImageList());
        rv_img.setAdapter(imageSelectAdapter);
        imageSelectAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ll_add_pic) {
                showCreamOrRecordVideoDialog();
            } else if (view.getId() == R.id.iv_view) {
                ImageSelectBean imageSelectBean = (ImageSelectBean) adapter.getData().get(position);
                String url = imageSelectBean.getImg();
                if (imageSelectBean.getImg().contains("mp4")) {
                    if (null != url) {
                        if (!url.contains("http") && url.startsWith("/api")) {
                            String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                            url = baseUrl + url;
                            Intent intent = new Intent(context, VideoPlaybackActivity.class);
                            intent.putExtra("videoUrl", url);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(context, VideoPlaybackActivity.class);
                            intent.putExtra("videoUrl", url);
                            startActivity(intent);
                        }
                    }


                    //showCenterPopupWindowPlayVideo(mLlHealth, list.get(position).getImg());
                } else {
                    showCenterPopupWindow(view, position, imageSelectAdapter.getData());
                }

            }
        });

        imageSelectAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                ImageSelectBean imageSelectBean = (ImageSelectBean) adapter.getData().get(position);
//22222222
                if (imageSelectBean.getType() != 0) {
                    CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_tip);
                    TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                    centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(v -> {
                        centerPopupWindow.dismiss();
                    });
                    tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_picture));
                    String url = imageSelectBean.getImg();
                    if (url.contains("mp4")) {
                        tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_video));
                    } else {
                        tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_picture));
                    }
                    TextView tvCancel = centerPopupWindow.getContentView().findViewById(R.id.tv_cancel);
                    TextView tvSure = centerPopupWindow.getContentView().findViewById(R.id.tv_sure);
                    tvCancel.setOnClickListener(view1 -> centerPopupWindow.dismiss());
                    tvSure.setOnClickListener(v -> {

                        //  presenter.deletePic(id, groupPosition, position);
                        centerPopupWindow.dismiss();
                        if (isHave00(adapter.getData())) {
                            item.getPictureUrls().remove(position - 1);
                        } else {
                            item.getPictureUrls().remove(position);
                        }
                        adapter.getData().remove(position);
                        imageSelectAdapter.addType00();
                        tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");

                    });
                    centerPopupWindow.show(rv_img);

                }
                return true;
            }
        });
    }


    @SuppressLint("SetTextI18n")
    private void initData() {
        databaseManager = new DatabaseManager(context);
        if (null != item) {
            tv_water_meter.setText(item.getMeterName());
            tv_normal_range_value.setText((null == item.getAlertLowLimit() ? "n" : item.getAlertLowLimit().stripTrailingZeros().toPlainString()) + "~" + (null == item.getAlertUpLimit() ? "n" : item.getAlertUpLimit().stripTrailingZeros().toPlainString()));
            tv_water_meter_name.setText(item.getMeterName());
            et_value.setText(item.getMeterRead());
            et_remake.setText(item.getRemark());
            tv_remake_font_count.setText((StringUtils.isEmpty(item.getRemark()) ? "0" : item.getRemark().length() + "") + "/100");
            tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");
            tv_remake_must.setVisibility(item.getMustFillRemark() == 1 ? View.VISIBLE : View.GONE);
            tv_photo_must.setVisibility(item.getMustTakePic() == 1 ? View.VISIBLE : View.GONE);
        }
    }

    private void initView() {
        tv_water_meter = findViewById(R.id.tv_water_meter);
        tv_water_meter_name = findViewById(R.id.tv_water_meter_name);
        tv_normal_range_value = findViewById(R.id.tv_normal_range_value);
        et_remake = findViewById(R.id.et_remake);
        et_value = findViewById(R.id.et_value);
        tv_remake_font_count = findViewById(R.id.tv_remake_font_count);
        rv_img = findViewById(R.id.rv_img);
        tv_dispatch_order = findViewById(R.id.tv_dispatch_order);
        tv_num = findViewById(R.id.tv_num);
        iv_back = findViewById(R.id.iv_back);
        tv_remake_must = findViewById(R.id.tv_remake_must);
        tv_photo_must = findViewById(R.id.tv_photo_must);
    }

    @Override
    protected WaterMeterPresenter createPresenter() {
        return new WaterMeterPresenter();
    }


    private void showCenterPopupWindow(View anchor, int position, List<ImageSelectBean> list) {
        CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_img);
        ViewPager viewPager = centerPopupWindow.getContentView().findViewById(R.id.viewPager);
        centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerPopupWindow.dismiss();
            }
        });

        ImageView iv_left = centerPopupWindow.getContentView().findViewById(R.id.iv_left);
        ImageView iv_right = centerPopupWindow.getContentView().findViewById(R.id.iv_right);
        iv_left.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            if (currentItem > 0) {
                viewPager.setCurrentItem(currentItem - 1, true); // true for smooth scroll
            }
        });
        iv_right.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            int totalItems = viewPager.getAdapter().getCount();
            if (currentItem < totalItems - 1) {
                viewPager.setCurrentItem(currentItem + 1, true); // true for smooth scroll
            }
        });
        recordList.clear();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getImg().contains("mp4") || list.get(i).getImg().contains("MP4") || TextUtils.isEmpty(list.get(i).getImg())) {
                continue;
            }
            ImageSelectBean imageSelectBean = list.get(i);
            String url = imageSelectBean.getImg();
            if (!url.contains("http") && url.startsWith("/api")) {
                String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                url = baseUrl + url;
            }
            imageSelectBean.setImg(url);
            recordList.add(imageSelectBean);
        }
        ImagePagerAdapter pagerAdapter = new ImagePagerAdapter(context, recordList);
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (recordList.size() == 1) {
                    iv_left.setVisibility(View.GONE);
                    iv_right.setVisibility(View.GONE);
                } else {
                    if (i <= 0) {
                        iv_left.setVisibility(View.GONE);
                        iv_right.setVisibility(View.VISIBLE);
                    } else if (i >= recordList.size() - 1) {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.GONE);
                    } else {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.VISIBLE);
                    }
                }
            }


            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        ImageSelectBean selectBean = list.get(position);
        int positionSelect = 0;
        for (int i = 0; i < recordList.size(); i++) {
            if (TextUtils.equals(selectBean.getImg(), recordList.get(i).getImg())) {
                positionSelect = i;
            }
        }
        if (positionSelect == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.VISIBLE);
        }
        if (recordList.size() == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.GONE);
        } else {
            if (positionSelect == 0) {
                iv_left.setVisibility(View.GONE);
                iv_right.setVisibility(View.VISIBLE);
            } else if (positionSelect == recordList.size() - 1) {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.GONE);
            } else {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.VISIBLE);
            }
        }
        viewPager.setCurrentItem(positionSelect);
        centerPopupWindow.show(anchor);
    }

    private String videoId = "";
    private String recordType = "";
    private static final int RECORDVIDEO = 20;

    private void showCreamOrRecordVideoDialog() {
        final CreamOrVideoRecordDialog dialog = new CreamOrVideoRecordDialog(this);
        dialog.show();
        dialog.setClickListener(new CreamOrVideoRecordDialog.ClickListenerInterface() {
            @Override
            public void takePhoto() {//拍照
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    permissionLists10.clear();
                    permissionLists11.clear();
                    permissionLists12.clear();
                    permissionLists13.clear();
                    //动态申请权限
                    applyPermissions(true, () -> nativeTakePhoto());
                } else {
                    nativeTakePhoto();
                }
                dialog.dismiss();
            }

            @Override
            public void recordVideo() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    applyPermissions(false, () -> {
                        Intent intent = new Intent();
                        videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                        intent.setClass(context, RecordVideoActivity.class);
                        startActivityForResult(intent, RECORDVIDEO);
                    });
                } else {
                    Intent intent = new Intent();
                    videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                    intent.setClass(context, RecordVideoActivity.class);
                    startActivityForResult(intent, RECORDVIDEO);
                }
                dialog.dismiss();
            }
        });
    }

    private void applyPermissions(boolean isCamera, RequestPermissionsListener listener) {

        if (Build.VERSION.SDK_INT >= 23) {
            permissionLists10.clear();
            permissionLists11.clear();
            permissionLists12.clear();
            permissionLists13.clear();
            //1.拍摄照片和录制内容
            //2。访问您设备上的照片。媒体文件内容和文件
            //3。录制视频
            //
            if (isCamera) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists10.add(Manifest.permission.CAMERA);
                }

                if (ContextCompat.checkSelfPermission(WaterMeterActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(WaterMeterActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }


                if (!permissionLists10.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists10.toArray(new String[permissionLists10.size()]), 10);
                    snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照和录制视频");
                } else if (!permissionLists13.isEmpty()) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (!permissionLists12.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    if (snackbar != null) {
                        snackbar.dismiss();
                    }
                    listener.requestSuccessCallback();
                }
                if (snackbar != null & rv_img != null) {
                    rv_img.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            snackbar.dismiss();
                        }
                    }, 3000);
                }
            } else {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists11.add(Manifest.permission.RECORD_AUDIO);
                }

                if (ContextCompat.checkSelfPermission(WaterMeterActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(WaterMeterActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

                if (!permissionLists11.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists11.toArray(new String[permissionLists11.size()]), 11);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (!permissionLists13.isEmpty()) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (!permissionLists12.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    if (snackbar != null) {
                        snackbar.dismiss();
                    }
                    listener.requestSuccessCallback();
                }
                if (snackbar != null & rv_img != null) {
                    rv_img.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            snackbar.dismiss();
                        }
                    }, 3000);
                }
            }

        }

    }


    /**
     * 拍照
     */
    public void nativeTakePhoto() {
        imageName = ImageUtils.getImageName(this) + ".jpg";
        if (Build.BRAND.equalsIgnoreCase("nokia")) {
            Utility.startPhotoActivityForH5(WaterMeterActivity.this, TAKEPIC_H5, ImageUtils.getH5ImagePath(imageName, context));
        } else {
            Intent intent = new Intent(this, CameraOneActivity.class);
            intent.putExtra("imagename", imageName);
            startActivityForResult(intent, TAKEPIC_H5);
            overridePendingTransition(0, 0);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKEPIC_H5) {
            //打开图片编辑页面
            //h5拍照,拍照成功返回结果是-1
            if (resultCode == -1) {
                Intent intent = new Intent(this, ImageEditActivity.class);
                intent.putExtra("imageName", imageName);
                intent.putExtra("locationDescribe", H5Activity.locationDescribe);
                intent.putExtra("intentType", 0);
                startActivityForResult(intent, IMAGEEDIT_OK);
            }

        } else if (requestCode == IMAGEEDIT_OK) {
            if (resultCode == Constant.EDITIMAGE_OK) {
                String pathUri = data.getStringExtra("pathuri");
                String path = data.getStringExtra("path");
                imageName = imageName.replace(".jpg", ".jpeg");
                if (NetworkUtils.isAvailable(context)) {
                    //上传图片
                    presenter.uploadImgForClient(path, path, imageName.split("\\.")[0]);
                } else {
                    onErrorUploadMethod(path, path, imageName.split("\\.")[0], "", false);

                }
            } else {
                //用户点了回退，删除刚拍照过的图片
                FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(imageName, this));
            }
        } else if (requestCode == RECORDVIDEO) {
            if (data != null) {
                //录制视频返回的url
                String url = data.getStringExtra(Constant.RECORD_VIDEO_OK);
                Log.e("2233333", url);
//                takePhotoEditVideoOkCallBack(videoId);
                uploadVideo(url, videoId);
            }
        } else if (requestCode == 20002) {
            if (resultCode == RESULT_OK) {
                if (null == data) {
                    return;
                }
                String json = data.getStringExtra("json");
                if (!StringUtils.isEmpty(json)) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("checkId")) {
                            String checkId = jsonObject.getString("checkId");
                            if (jsonObject.has("orderId")) {
                                String orderId = jsonObject.getString("orderId");
                                item.setWorkOrderId(orderId);


                            }
                        }


                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (null != recordItem && recordPosition != -1) {
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) { //当前有必填项 未填
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    item.setAbnormal(1);
                    recordItem = null;
                    recordPosition = -1;
                }

            }


        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartH5Event event) {
        if (event == null) return;
        String json = event.getJson();
        if (!StringUtils.isEmpty(json)) {
            try {
                JSONObject jsonObject = new JSONObject(json);
                if (jsonObject.has("checkId")) {
                    String checkId = jsonObject.getString("checkId");
                    if (jsonObject.has("orderId")) {
                        String orderId = jsonObject.getString("orderId");
                        item.setWorkOrderId(orderId);
                    }
                }
                if (null != recordItem && recordPosition != -1) {
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) { //当前有必填项 未填
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }//在这判断是否异常
                    item.setAbnormal(1);
                    recordItem = null;
                    recordPosition = -1;
                }
                setBackData();

            } catch (JSONException e) {
                throw new RuntimeException(e);
            }

        }


    }

    @Override
    public void uploadImgForClientSuccess(UploadImage baseData, String locationUrl) {
        if (null != baseData) {
            List<UploadImage.RecordBean> record = baseData.getRecord();
            if (null != record && !record.isEmpty()) {
                UploadImage.RecordBean recordBean = record.get(0);
                if (null != recordBean) {
                    String url = recordBean.getUrl();
                    String markersUrl = recordBean.getThumburl();
                    String picId = recordBean.getId();
                    presenter.updateInspectionPointWorkRequest(picId, url, markersUrl, item.getId(), locationUrl, item.getTitle(), true);
                }
            }
        }

    }

    @Override
    public void uploadImgForClientOnError(String uploadUrl, String locationUrl, String id) {
        onErrorUploadMethod(uploadUrl, locationUrl, id, "", false);
    }

    @Override
    public void updateInspectionPointWorkRequestSuccess(String picId, String url, String shrinkUrl, boolean isPic) {
        if (isPic) {
            // url = presenter.getSharedPrefs().getString(Constant.BASE_ADDRESS_URL, "") + url;
            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
            pictureUrlsDTO.setUrl(url);
            pictureUrlsDTO.setThumburl(shrinkUrl);
            pictureUrlsDTO.setId(picId);
            item.getPictureUrls().add(pictureUrlsDTO);
            //String picUrl = presenter.getSharedPrefs().getString(Constant.BASE_ADDRESS_URL, "") + url;

            List<ImageSelectBean> beanImgList = imageSelectAdapter.getData();
            beanImgList.add(new ImageSelectBean(url, 1));
            if (beanImgList.size() > 9) {
                removeAdd(beanImgList);
            }
            imageSelectAdapter.setNewData(beanImgList);
            imageSelectAdapter.notifyDataSetChanged();
            tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");
            //上传成功后删除该图片
            FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(picId + ".jpeg", this));
        } else {
            ToastMessage(getResources().getString(R.string.upload_success));
            //  url = presenter.getSharedPrefs().getString(Constant.BASE_ADDRESS_URL, "") + url;
            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
            pictureUrlsDTO.setUrl(url);
            pictureUrlsDTO.setThumburl(url);
            pictureUrlsDTO.setId(picId);
            item.getPictureUrls().add(pictureUrlsDTO);
            addVideoList(url);

        }
        isCheckPass();
    }

    private void removeAdd(List<ImageSelectBean> imageList) {
        for (int i = 0; i < imageList.size(); i++) {
            if (imageList.get(i).getType() == 0) {
                imageList.remove(i);
            }
        }
    }

    @Override
    public void updateInspectionPointWorkRequestFail(String picId, String url, String shrinkUrl, String locationUrl, boolean isPic) {
        if (isPic) {
            onErrorUploadMethod(url, locationUrl, picId, shrinkUrl, true);
        }

    }

    private void onErrorUploadMethod(String uploadUrl, String locationUrl, String id, String shrinkUrl, boolean isHaveShrinkUrl) {
        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
        pictureUrlsDTO.setUrl(uploadUrl);
        pictureUrlsDTO.setId(id);
        pictureUrlsDTO.setThumburl(uploadUrl);
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list = item.getPictureUrls();
        if (null != list) {
            list.add(pictureUrlsDTO);
        }
        item.setPictureUrls(list);

        List<ImageSelectBean> beanImgList = imageSelectAdapter.getData();
        beanImgList.add(new ImageSelectBean(locationUrl, 1));
        if (beanImgList.size() > 9) {
            removeAdd(beanImgList);
        }
        imageSelectAdapter.setNewData(beanImgList);
        tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");

        //存到数据库
        Map<String, Object> map = new HashMap<>();
        map.put("ids", id);
        map.put("url", uploadUrl);
        String json = new Gson().toJson(map);
        //databaseManager.insertInspectPic(json);
        String pointId = getIntent().getStringExtra("pointId");
        String listId = getIntent().getStringExtra("listId");
        String des = getIntent().getStringExtra("des");
        new ImageCompressor(context).compressImageInPlace(uploadUrl, new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                CacheHelper.getInstance().addUploadImage(listId, pointId, new ImageUploadBean(file.getPath(), file.getPath(), id, item.getTitle(), pointId, item.getId()), des);

            }

            @Override
            public void onError(Throwable e) {

            }
        });

    }

//    @Override
//    public void deletePicSuccess(int groupPosition, int position) {
//        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = startWorkAdapter.getItem(groupPosition).getPictureUrls().get(position);
//        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> pictureUrls = startWorkAdapter.getItem(groupPosition).getPictureUrls();
//        pictureUrls.remove(pictureUrlsDTO);
//        //isShowEmpty(groupPosition);
//        startWorkAdapter.notifyItemChanged(groupPosition);
//
//    }

    public boolean isHave00(List<ImageSelectBean> list) {
        boolean isHave = false;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getType() == 0) {
                isHave = true;
            }
        }
        return isHave;
    }

    public void uploadVideo(final String localUrl, String ids) {
        File files = new File(localUrl);
        if (!files.exists()) {
            return;
        }
//        loadingDialog.setText(getResources().getString(R.string.uploading));
        showLoading();
        presenter.uploadVideo(localUrl, ids, files);
    }


    @Override
    public void uploadVideoSuccess(String url, String localUrl, String id) {
        presenter.updateInspectionPointWorkRequest(id, url, url, item.getId(), localUrl, item.getTitle(), false);
        //这里在适配器里更新
    }

    public void addVideoList(String videoUrl) {
        List<ImageSelectBean> beanImgList = imageSelectAdapter.getData();
        beanImgList.add(new ImageSelectBean(videoUrl, 2));
        if (beanImgList.size() > 9) {
            removeAdd(beanImgList);
        }
        imageSelectAdapter.setNewData(beanImgList);
        imageSelectAdapter.notifyDataSetChanged();
        tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");

    }

}
